﻿using DotNetty.Extensions;
using System.Net;
using System.Text;

var udp = new UdpSocket(8888);

udp.OnStarting += () =>
{
    Console.WriteLine("Starting...");
};

udp.OnStarted += async () =>
{
    Console.WriteLine("Started.");

    var endPoint = new IPEndPoint(IPAddress.Broadcast, 7777);
    var bytes = Encoding.UTF8.GetBytes("this is from UDP2 message!");
    await udp.WriteAndFlushAsync(endPoint, bytes);

    await udp.WriteAndFlushAsync("127.0.0.1:7777", bytes);
};

udp.OnStopped += async ex =>
{
    Console.WriteLine($"Stopped==>{ex?.Message}");
    await Task.Delay(2000);
    await udp.StartAsync(); //reconnect
};

udp.OnException += ex =>
{
    Console.WriteLine($"Exception==>{ex?.Message}");
};

udp.OnMessage += (endPoint, bytes) =>
{
    Console.WriteLine(endPoint);
    Console.WriteLine(Encoding.UTF8.GetString(bytes));

};

await udp.StartAsync();

Console.ReadKey();

await udp.DisposeAsync();

Console.WriteLine("Hello, World!");
